package com.dhcc.core.modules.common.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;

/**
 * 文件控制器
 * 
 * @ClassName: FileController
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:18:51
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

    @Autowired
    private SysProperties sysProperties;

    /**
     * 上传文件
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile file) {
        String fileSavePath = "upload" + File.separator + DateUtil.getYearMonth() + File.separator;
        File dir = new File(sysProperties.getFileUploadPath() + fileSavePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName = UUID.randomUUID().toString() + "." + getExtensionName(file.getOriginalFilename());
        try {
            file.transferTo(new File(sysProperties.getFileUploadPath() + fileSavePath + fileName));
        } catch (Exception e) {
            throw new BizException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return fileSavePath + fileName;
    }

    /**
     * 返回文件
     *
     * @author cyf
     * @Date 2017/5/24 23:00
     */
    @RequestMapping("/download/**")
    public void renderFile(HttpServletRequest request, HttpServletResponse response) {
        String tagname = extractPathFromPattern(request);
        String path = sysProperties.getFileUploadPath() + tagname;
        ServletOutputStream outputStream = null;
        try {
            File file = new File(path);
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + setFileDownloadHeader(request, file.getName()));
            InputStream myStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            IOUtils.copy(myStream, outputStream);
            IOUtils.closeQuietly(outputStream);
            response.flushBuffer();
        } catch (Exception e) {
            String extensionName = getExtensionName(tagname);
            if (CommonUtil.equals(extensionName, "jpg") || CommonUtil.equals(extensionName, "jpeg")
                    || CommonUtil.equals(extensionName, "gif") || CommonUtil.equals(extensionName, "png")) {
                // 如果找不到图片就返回一个默认图片
                try {
                    response.sendRedirect(getContextPath() + "/static/common/img/webuploader.png");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                throw new BizException("文件不存在！");
            }
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
        ;
    }

    /**
     * 返回文件
     *
     * @author cyf
     * @Date 2017/5/24 23:00
     */
    @RequestMapping("/image/**")
    public void renderImage(HttpServletRequest request, HttpServletResponse response) {
        String tagname = extractPathFromPattern(request);
        String path = sysProperties.getFileUploadPath() + tagname;
        ServletOutputStream outputStream = null;
        try {
            File file = new File(path);
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + setFileDownloadHeader(request, file.getName()));
            InputStream myStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            IOUtils.copy(myStream, outputStream);
        } catch (Exception e) {
            // 如果找不到图片就返回一个默认图片
            try {
                response.sendRedirect(getContextPath() + "/static/common/img/webuploader.png");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
        ;
    }

    /**
     * 把指定URL后的字符串全部截断当成参数 这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * 
     * @param request
     * @return
     */
    private String extractPathFromPattern(HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

    /*
     * Java文件操作 获取文件扩展名
     *
     * Created on: 2011-8-2 Author: blueeagle
     */
    private String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 兼容多浏览器
     * 
     * @Title: setFileDownloadHeader
     * @Description: TODO
     * @param request
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     * @return: String
     */
    public String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

}
